package cn.itcast.bos.service.base.impl;

import cn.itcast.bos.dao.AreaDao;
import cn.itcast.bos.dao.FixedAreaDao;
import cn.itcast.bos.dao.OrderDao;
import cn.itcast.bos.dao.WorkBillDao;
import cn.itcast.bos.domain.base.*;
import cn.itcast.bos.domain.contant.Constant;
import cn.itcast.bos.domain.take_delivery.Order;
import cn.itcast.bos.domain.take_delivery.WorkBill;
import cn.itcast.bos.service.base.OrderService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;
import java.util.Date;
import java.util.Iterator;
import java.util.UUID;

@Transactional
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDao orderDao;

    @Autowired
    private FixedAreaDao fixedAreaDao;
    @Autowired
    private AreaDao areaDao;
    @Autowired
    private WorkBillDao workBillDao;
    @Autowired
    @Qualifier("jmsQueueTemplate")
    private JmsTemplate jmsTemplate;
    @Override
    public void saveOrder(Order order) {
        System.out.println(order);
        order.setOrderNum(UUID.randomUUID().toString());
        order.setOrderTime(new Date());
        order.setStatus("1");//代取件
        Area area = order.getSendArea();
        Area persistArea = areaDao.findByProvinceAndCityAndDistrict(area.getProvince(),area.getCity(),area.getDistrict());
        //收件人 省市区
        Area recArea = order.getRecArea();
        Area persistRecArea = areaDao.findByProvinceAndCityAndDistrict(recArea.getProvince(),recArea.getCity(),recArea.getDistrict());

        order.setSendArea(persistArea);
        order.setRecArea(persistRecArea);
    //自动分单逻辑 ,给予CRM地址库完全匹配,获取定区,匹配快递员
       String fixedAreaId = WebClient.create(Constant.CRM_MANAGEMENT_URL+"/services/customerService/customer/findFixedAreaIdByAddress?address="+order.getSendAddress()).
               accept(MediaType.APPLICATION_JSON).get(String.class);

       if (fixedAreaId !=null) {
           FixedArea fixedArea = fixedAreaDao.findOne(fixedAreaId);
           Courier courier = fixedArea.getCouriers().iterator().next();
           if (courier !=null) {
               //自动分单成功
               System.out.println("自动分单成功-------------------------------");
               saveOrder(order,courier);
               //生成工单发短信
               generateWorkBill(order);
               return;
           }
       }
        //自动分单 逻辑, 通过省市区, 查询分区关键字,匹配地址,给予分区实现自动分单
        for (SubArea subArea :persistArea.getSubareas()){
           if(order.getSendAddress().contains(subArea.getKeyWords())){
               Iterator<Courier> iterator = subArea.getFixedArea().getCouriers().iterator();
               if (iterator.hasNext()) {
                   Courier courier = iterator.next();
                   if (courier !=null) {
                       //自动分单成功
                       System.out.println("自动分单成功------------");
                       saveOrder(order,courier);
                       //生成工单,发送短信
                       generateWorkBill(order);
                       return;
                   }
               }
           }
        }
        for (SubArea subArea :persistArea.getSubareas()){
            if(order.getSendAddress().contains(subArea.getAssistKeyWords())){
                Iterator<Courier> iterator = subArea.getFixedArea().getCouriers().iterator();
                if (iterator.hasNext()) {
                    Courier courier = iterator.next();
                    if (courier !=null) {
                        //自动分单成功
                        System.out.println("自动分单成功------------");
                        saveOrder(order,courier);
                        //生成工单,发送短信
                        generateWorkBill(order);
                        return;
                    }
                }
            }
        }
        //进入人工分单
        order.setOrderType("2");
        orderDao.save(order);
    }

    @Override
    public Order findOrderByOrderNum(String orderNum) {
        return orderDao.findByorderNum(orderNum);
    }

    private void generateWorkBill(Order order) {
        //生成工单
        WorkBill workBill = new WorkBill();
        workBill.setType("新");
        workBill.setPickstate("新单");
        workBill.setBuildtime(new Date());
        workBill.setRemark(order.getRemark());
        final String smsNumber = RandomStringUtils.randomNumeric(4);
        workBill.setSmsNumber(smsNumber);
        workBill.setOrder(order);
        workBill.setCourier(order.getCourier());
        workBillDao.save(workBill);

        //发送短信调用MQ服
        jmsTemplate.send("ordersms", new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                Message message = session.createMessage();
                message.setStringProperty("telephone", order.getCourier().getTelephone());
                message.setStringProperty("msg", "sdfsdfsdffsdxingsdfsdfsfddfsf");

                return message;
            }
        });
        //自动分单保存
        workBill.setPickstate("已通知");
    }
    private void saveOrder(Order order, Courier courier) {
        order.setCourier(courier);
        order.setOrderType("1");
        orderDao.save(order);
    }
}
